package com.xg.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xg.common.response.TokenResponse;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.HashMap;

/**
 * JWT令牌
 */
public class JWTUtils {

    // yan
    private static String SIGN = "#*(^$&*#%!(&hbfd123";

    // 手机号
    private static final String JWT_KEY_PHONE = "userPhone";
    // 用户名
    private static final String JWT_KEY_USERNAME = "username";

    // 防止token重复
    private static final String JWT_TOKEN_DATE = "tokenTime";

    /**
     * 生成token
     */
    public static String genertorToken(String userPhone,String username){
        HashMap<String, String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE,userPhone);
        map.put(JWT_KEY_USERNAME,username);
        map.put(JWT_TOKEN_DATE, Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * 解码
     */
    public static TokenResponse parseToken(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        // toString 会在前后加“” , 而verify本身自带“”，所以使用asString
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String username = verify.getClaim(JWT_KEY_USERNAME).asString();
        TokenResponse tokenResponse = new TokenResponse();
        if (StringUtils.hasLength(phone)){
            tokenResponse.setUserPhone(phone);
        }
        if (StringUtils.hasLength(username)){
            tokenResponse.setUsername(username);
        }
        return tokenResponse;
    }

    /**
     * 校验token
     */
    public static TokenResponse checkToken(String token){
        TokenResponse tokenResponse = null;
        try {
            tokenResponse = JWTUtils.parseToken(token);
        }catch (Exception e){

        }

        return tokenResponse;
    }

}
